package com.heima.wemedia.service.impl;

import com.heima.api.IScheduleClientFeign;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.nio.charset.StandardCharsets;
import java.util.Date;

public class WmNewsTaskServiceimpl implements WmNewsTaskService {


    @Autowired
    private IScheduleClientFeign iScheduleClientFeign;

    @Autowired
    private  WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {

        //远程调用
        Task task=new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        //开始序列化
        WmNews wmNews =new WmNews();
        wmNews.setId(id);
        byte[] bytes= ProtostuffUtil.serialize(wmNews);

        task.setParameters(bytes);
        //2.调用自动审核业务
        iScheduleClientFeign.addTask(task);
    }

    @Override
    @Scheduled()
    public void scanNewsByTask() {
        //调用feign接口
        Integer taskType = TaskTypeEnum.NEWS_SCAN_TIME.getTaskType();
        Integer priority = TaskTypeEnum.NEWS_SCAN_TIME.getPriority();
        Task task = iScheduleClientFeign.pullTask(taskType,priority);
        if (task!=null){
            byte[] parameters = task.getParameters();
            if (parameters.length>0){
                //反序列化
                WmNews wmNews = ProtostuffUtil.deserialize(parameters,WmNews.class);
                wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
            }
        }
    }
}
